package com.listen.playanddown.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.RemoteViews;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.listen.playanddown.Application;
import com.listen.playanddown.IMusicService;
import com.listen.playanddown.NoFastClickUtils;
import com.listen.playanddown.PlayActivity;
import com.listen.playanddown.R;
import com.listen.playanddown.bean.ChangeNotifi;
import com.listen.playanddown.bean.MusicBean;
import com.listen.playanddown.bean.PercentBean;
import com.listen.playanddown.bean.PlayClick;
import com.wgl.android.library.baserx.RxManager;

import java.io.IOException;
import java.util.List;

import rx.functions.Action1;

public class MusicService extends Service implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    public MusicService() {
    }

    protected RxManager mRxManager;

    //创建Service
    @Override
    public void onCreate() {
        super.onCreate();
        //创建RxBus
        mRxManager = new RxManager();
        //接收改变状态栏的消息，0为暂停，1位播放
        mRxManager.on("changeNotifi", new Action1<ChangeNotifi>() {
            @Override
            public void call(ChangeNotifi changeNotifi) {
                //
                if (contentView != null) {
                    if (changeNotifi.getStatus() == 0) {
                        contentView.setImageViewResource(R.id.notifi_start, R.drawable.notify_btn_dark_play_normal);
                    } else if (changeNotifi.getStatus() == 1) {
                        contentView.setImageViewResource(R.id.notifi_start, R.drawable.notify_btn_dark_pause_normal);
                    }
                    //刷新状态栏
                    manager.notify(id, notification);
                }
            }
        });

        mRxManager.on("notifi", new Action1<PlayClick>() {
            @Override
            public void call(PlayClick playClick) {
                Log.e("-----playClick", "===" + playClick.getI());
                if (playClick.getI() == 0) {
                    if (mediaPlayer.isPlaying()) {
                        puaseMusic();
                        contentView.setImageViewResource(R.id.notifi_start, R.drawable.notify_btn_dark_play_normal);

                    } else {
                        playMusic();
                        contentView.setImageViewResource(R.id.notifi_start, R.drawable.notify_btn_dark_pause_normal);
                    }
                    manager.notify(id, notification);
                } else {
                    if (!NoFastClickUtils.isFastClick()) {
                        playNext();
                    }
                }
            }
        });

    }

    @Override
    public boolean onUnbind(Intent intent) {
//        manager.cancel(id);
//        manager.cancelAll();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {

        manager.cancel(id);
        manager.cancelAll();
        mRxManager.clear();
        super.onDestroy();
    }

    //绑定服务，返回aidl
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }

    //创建aidl、调用service的方法
    IMusicService.Stub stub = new IMusicService.Stub() {
        @Override
        public void openMusic(int position) throws RemoteException {
            MusicService.this.openMusic(position);
        }

        @Override
        public int getCurrentPosition() throws RemoteException {
            return MusicService.this.getCurrentPosition();
        }


        @Override
        public void playMusic() throws RemoteException {
            MusicService.this.playMusic();
        }

        @Override
        public void puaseMusic() throws RemoteException {
            MusicService.this.puaseMusic();
        }

        @Override
        public void stopMusic() throws RemoteException {
            MusicService.this.stopMusic();
        }

        @Override
        public String getUrl() throws RemoteException {
            return MusicService.this.getUrl();
        }

        @Override
        public String getImageUrl() throws RemoteException {
            return MusicService.this.getImageUrl();
        }

        @Override
        public String getProgress() throws RemoteException {
            return MusicService.this.getProgress();
        }

        @Override
        public String getTime() throws RemoteException {
            return MusicService.this.getTime();
        }

        @Override
        public String getName() throws RemoteException {
            return MusicService.this.getName();
        }

        @Override
        public String getAuthor() throws RemoteException {
            return MusicService.this.getAuthor();
        }

        @Override
        public void playTop() throws RemoteException {
            MusicService.this.playTop();
        }

        @Override
        public void playNext() throws RemoteException {
            MusicService.this.playNext();
        }

        @Override
        public boolean isPlaying() throws RemoteException {
            return MusicService.this.isPlaying();
        }

        @Override
        public void seekTo(int position) throws RemoteException {
            MusicService.this.seekTo(position);
        }

        @Override
        @TargetApi(23)
        public void setPlaySpeed(double speed) throws RemoteException {
            mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed((float) speed));
        }


    };

    //得到图片url
    private String getImageUrl() {
        if (mediaPlayer != null)
            return music.getThumbnail() + "";
        else return "";
    }

    //获取AudioManager，可以管理音乐播放状态
    private AudioManager audioManager;

    //获取焦点，防止一次播放2个音乐
    private boolean tryToGetAudioFocus() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            return true;
        }
        return false;
    }

    private MediaPlayer mediaPlayer;

    //创建MediaPlayer
    private void createMediaPlayerIfNeeded() {
        //如果当前播放器没有，则创建播放器
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            //设置屏幕不黑 、、需要权限WAKE_LOCK
//            mediaPlayer.setWakeMode(getApplicationContext(),
//                    PowerManager.PARTIAL_WAKE_LOCK);
            //设置播放器的监听事件,
            //准备播放
            mediaPlayer.setOnPreparedListener(this);
            //播放完成
            mediaPlayer.setOnCompletionListener(this);
            //播放出错
            mediaPlayer.setOnErrorListener(this);
        } else {
            mediaPlayer.reset();
        }
    }

    //stop音乐，暂未使用
    private void relaxResources() {
        //  从前台状态删除该服务，允许它被杀死
        stopForeground(true);
        //如果播放器不为空
        if (mediaPlayer != null) {
            //并且是在播放状态
            if (mediaPlayer.isPlaying()) {
                //则让播放器停止
                mediaPlayer.stop();
            }
            //释放资源：mediaPlayer.release()并设null
//            mediaPlayer.reset();
//            mediaPlayer = null;
        }
    }

    //从Application中获取播放源
    private List<MusicBean.MsgEntity.DataEntity> data;
    //当前播放的音乐
    private MusicBean.MsgEntity.DataEntity music;
    //当前播放的position
    private int currentPosition;

    //播放当前音乐，点击一个item走此方法
    private void openMusic(int position) {
        //判断是否拥有焦点
        if (tryToGetAudioFocus()) {
            //当前position=播放的position
            currentPosition = position;
            //存入Applicition，暂未使用
            Application.setPlayPosition(currentPosition);
            //获取数据源
            data = Application.getData();
            //获取当前音乐
            music = data.get(position);

            try {
                //如果当前播放器没有，则创建播放器
                createMediaPlayerIfNeeded();
                //设置了类型为music
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                //设置播放的url资源地址
                mediaPlayer.setDataSource(getUrl());
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //获取当前播放的音乐，如果第一次进入没有播放的则返回-1
    private int getCurrentPosition() {
        if (mediaPlayer != null)
            return currentPosition;
        else return -1;
    }


    //播放
    private void playMusic() {
        if (mediaPlayer != null) {
            //如果不为null丙炔不是播放状态
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                //渐强的时长，单位：毫秒；默认2秒
                final long duration = 2000;
                //音量调节的时间间隔
                long interval = duration / 10;
                new CountDownTimer(duration, interval) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        float volume = 1f - millisUntilFinished * 1.0f / duration;
                        mediaPlayer.setVolume(volume, volume);
                    }

                    @Override
                    public void onFinish() {
                        mediaPlayer.setVolume(1f, 1f);

                    }
                }.start();
            }
        }
    }

    //暂停
    private void puaseMusic() {
        //如果播放器不为空
        if (mediaPlayer != null) {
            //
            //渐强的时长，单位：毫秒；默认2秒
            final long duration = 1000;
            //音量调节的时间间隔
            long interval = duration / 20;
            new CountDownTimer(duration, interval) {

                @Override
                public void onTick(long millisUntilFinished) {
                    float volume = millisUntilFinished * 1.0f / duration;
                    mediaPlayer.setVolume(volume, volume);
                }

                @Override
                public void onFinish() {
                    mediaPlayer.setVolume(0f, 0f);
                    mediaPlayer.pause();
                    //放弃当前音乐的焦点，防止一次播放两个音乐
                    giveUpAudioFocus();
                }
            }.start();

        }
    }

    //stop暂未使用
    private void stopMusic() {
        //放弃焦点
        giveUpAudioFocus();
        relaxResources();
    }

    private void giveUpAudioFocus() {
        //放弃当前音乐的焦点，防止一次播放两个音乐
        audioManager.abandonAudioFocus(this);
    }

    //获取当前播放的mp3地址
    private String getUrl() {
        if (mediaPlayer != null) {
            return music.getMp3();
        }
        return "";
    }

    //获取当前播放进度
    private String getProgress() {
        if (mediaPlayer != null)
            return mediaPlayer.getCurrentPosition() + "";
        else return "0";
    }

    //获取作者
    private String getAuthor() {
        if (mediaPlayer != null) {
            return music.getTitle();
        }
        return "";
    }

    //得到总时间
    private String getTime() {
        if (mediaPlayer != null) {
            return music.getMp3_duration();
        }
        return "";
    }

    //得到音乐的标题
    private String getName() {
        if (mediaPlayer != null) {
            return music.getTitle();
        }
        return "";
    }

    //播放上一首，此为顺序播放，以后添加播放模式
    private void playTop() {

        currentPosition--;
        if (currentPosition < 0) {
            //  openMusic(++position);
            ++currentPosition;
        } else {
            openMusic(currentPosition);
        }
    }

    //播放下一首，此为顺序播放，以后添加播放模式
    private void playNext() {
        currentPosition++;
        if (currentPosition < data.size()) {
            openMusic(currentPosition);
        } else {

//            openMusic(--position);
            --currentPosition;
        }

    }

    //判断当前音乐是否在播放
    private boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    //移动进度条
    private void seekTo(int position) {
        mediaPlayer.seekTo(position);
    }


    //不知道有啥用
    private boolean canDuck = false;
    public static final float VOLUME_DUCK = 0.2f;
    public static final float VOLUME_NORMAL = 1.0f;

    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN:
                if (canDuck) {
                    mediaPlayer.setVolume(VOLUME_NORMAL, VOLUME_NORMAL);
                } else {
                    if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                    }
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    stopMusic();
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    puaseMusic();
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                mediaPlayer.setVolume(VOLUME_DUCK, VOLUME_DUCK);
                canDuck = true;
                break;
        }
    }

    //

    @Override
    public void onPrepared(MediaPlayer mp) {
        //准备好，如果播放器不为null，并且不是播放状态
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer arg0, int percent) {
                   /* 打印缓冲的百分比, 如果缓冲 */
                    System.out.println("缓冲了的百分比 : " + percent + " %");
                    PercentBean p = new PercentBean();
                    p.setPercent(percent);
                    mRxManager.post("percent", p);
                }
            });

            //准备好，开始播放
            mediaPlayer.start();
            //准备好了，发送刷新页面的消息
            mRxManager.post("updatePage", music);
            //创建状态通知栏
            createCustomNotification();
        }
    }

    /**
     * 自定义通知
     */
    private int id = 1;
    private RemoteViews contentView;
    private Notification notification;
    private NotificationManager manager;

    //2个点击事件的广播接收器


    private void createCustomNotification() {
        int icon = R.mipmap.ic_launcher;//没打开通知栏时显示的小图标
        long when = System.currentTimeMillis();
        //必须要有这三个参数，不然出来的状态栏显示不全
        notification = new Notification(icon, getName(), when);
        //创建layout
        contentView = new RemoteViews(this.getPackageName(), R.layout.notification);
        //设置textview的值
        contentView.setTextViewText(R.id.title, getName());
        contentView.setTextViewText(R.id.text, getAuthor());
        //R.id.to_play点击事件：进入播放页面  注：需要设置PlayActivity为单例模式，否则会打开多个页面
        Intent to_play = new Intent(MusicService.this, PlayActivity.class);
        to_play.putExtra("position", currentPosition);
        PendingIntent to_playPi = PendingIntent.getActivity(this, 1, to_play, PendingIntent.FLAG_UPDATE_CURRENT);
        contentView.setOnClickPendingIntent(R.id.to_play, to_playPi);


        //暂停点击事件：发送暂停广播
        Intent intent = new Intent();
        intent.setAction("com.hzjm.notifi");
        intent.putExtra("action", 0);
        PendingIntent intentpi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        contentView.setOnClickPendingIntent(R.id.notifi_start, intentpi);
        //下一首：发送下一首广播
        Intent intent2 = new Intent();
        intent2.setAction("com.hzjm.notifi");
        intent2.putExtra("action", 1);
        PendingIntent intentpi2 = PendingIntent.getBroadcast(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        contentView.setOnClickPendingIntent(R.id.notifi_next, intentpi2);


        notification.contentView = contentView;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        //       notification.defaults = Notification.DEFAULT_SOUND;//打开声音
        manager = (NotificationManager) MusicService.this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(id, notification);
        // 更新网络图标，在显示文字等之后调用，因为联网需花时间，等请求后再更新状态栏
        Glide.with(MusicService.this).load(music.getThumbnail()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                contentView.setImageViewBitmap(R.id.image, resource);
                manager.notify(id, notification);
            }
        });
//        startForeground(1, notification);
        stopForeground(true);

    }


    //播放完成，播放下一首
    @Override
    public void onCompletion(MediaPlayer mp) {
        playNext();
    }

    //播放出错，播放下一首
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        playNext();
        return true;
    }


}
